﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Newtonsoft.Json;

namespace working
{
    public partial class MainForm : Form
    {
        private GetForm getForm;
        private DetailForm detailForm;
        private BackupForm backupForm;
        private SettingLinkForm settingLinkForm;
        private View.SettingCmdForm settingCmdForm;
        private List<WorkItem> workItems = new List<WorkItem>();
        private List<WorkItem> fliterdWorkItems = new List<WorkItem>();
        private List<Button> quickBtns = new List<Button>();
        private bool sortRe;
        private CmdAgent agent;
        private ConfigLogic configLogic { get { return ConfigLogic.Instence; } }
        private string fliter_key { get { return match_box.Text; } }
        private List<WorkItem> ShowItems
        {
            get
            {
                if (string.IsNullOrEmpty(fliter_key))
                {
                    return workItems;
                }
                else
                {
                    return fliterdWorkItems;
                }
            }
        }
        private WorkItem selectedItem { get; set; }
        private int selectedId { get; set; }
        public MainForm()
        {
            InitializeComponent();
            agent = new CmdAgent();
            listView1.MouseClick += OnMouseClickItem;
            listView1.DoubleClick += OnMouseDoubleClickItem;
            listView1.ColumnClick += OnColumClick;
            match_box.TextChanged += OnUpdateFliter;
            getForm = new GetForm();
            getForm.onApply = OnApplyGetFormItem;

            detailForm = new DetailForm();
            detailForm.onApply = OnApplyDetailItem;
            detailForm.onHide = OnHideDetailItem;

            backupForm = new BackupForm();
            backupForm.onChange = OnSelectedItemChanged;

            settingLinkForm = new SettingLinkForm();
            settingLinkForm.onChange = ReloadLinksToView;

            settingCmdForm = new View.SettingCmdForm();
            settingCmdForm.onChange = ReLoadCmdListToView;

            quickBtns = new List<Button>() { quickbtn1, quickbtn2, quickbtn3, quickbtn4, quickbtn5 };
            LoadDatasFromFolder();
            SortWorkItemByDefult();
            ReloadListView();
            ReloadLinksToView();
            LoadButtonCmdTexts();
        }
        private void OnHideDetailItem()
        {
            Visible = true;
        }


        private void OnUpdateFliter(object sender, EventArgs e)
        {
            UpdateListByFliter();
        }

        private void UpdateListByFliter()
        {
            if (!string.IsNullOrEmpty(fliter_key))
            {
                fliterdWorkItems.Clear();
                foreach (var item in workItems)
                {
                    var keyward = item.name + item.id + item.tags + item.source;
                    if (checkBox1_info.Checked)
                    {
                        keyward += item.description;
                    }
                    if (keyward.ToLower().Contains(fliter_key))
                    {
                        fliterdWorkItems.Add(item);
                    }
                }
            }
            ReloadListView();
        }

        private void OnColumClick(object sender, ColumnClickEventArgs e)
        {
            sortRe = !sortRe;
            var state = sortRe ? 1 : -1;
            if (e.Column == 0)
            {
                workItems.Sort((x, y) =>
                {
                    return state * string.Compare(x.id, y.id);
                });
            }
            else if (e.Column == 1)
            {
                workItems.Sort((x, y) =>
                {
                    return state * string.Compare(x.source, y.source);
                });
            }
            else if (e.Column == 2)
            {
                workItems.Sort((x, y) =>
                {
                    return state * string.Compare(x.name, y.name);
                });
            }
            else if (e.Column == 3)
            {
                workItems.Sort((x, y) =>
                {
                    return state * DateTime.Compare(x.time, y.time);
                });
            }
            else if (e.Column == 4)
            {
                workItems.Sort((x, y) =>
                {
                    return state * string.Compare(x.tags, y.tags);
                });
            }
            ReloadListView();
        }

        private void OnApplyDetailItem(WorkItem item)
        {
            if (item != null)
            {
                SaveChangedItemToFolder(item);
                ReloadListView();
            }
        }

        private void OnApplyGetFormItem(WorkItem item)
        {
            if (!this.workItems.Contains(item))
            {
                workItems.Add(item);
            }
            SaveChangedItemToFolder(item);
            ReloadListView();
        }

        private void LoadDatasFromFolder()
        {
            workItems.Clear();
            var dirs = Directory.GetDirectories(Util.GetRoot());
            for (int i = 0; i < dirs.Length; i++)
            {
                var configFile = Util.GetConfigFromFolder(dirs[i]);
                if (System.IO.File.Exists(configFile))
                {
                    var text = System.IO.File.ReadAllText(configFile);
                    if (!string.IsNullOrEmpty(text))
                    {
                        var workItem = JsonConvert.DeserializeObject<WorkItem>(text);
                        if (workItem != null)
                        {
                            workItem.Repire();
                            workItems.Add(workItem);
                        }
                    }
                }
            }
        }

        private void SortWorkItemByDefult()
        {
            workItems.Sort((x, y) =>
            {
                return -string.Compare(x.id, y.id);
            });
        }

        private void SaveChangedItemToFolder(WorkItem item)
        {
            if (item == null || string.IsNullOrEmpty(item.id)) return;
            var folder = Util.GetBranchFolder(item.id);
            var configFile = Util.GetConfigFromFolder(folder);
            if (File.Exists(configFile))
            {
                MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                DialogResult rt = MessageBox.Show("文件已经存,是否替换？", "保存配制", messButton);
                if (rt == DialogResult.Cancel)
                {
                    return;
                }
            }

            var json = JsonConvert.SerializeObject(item);
            System.IO.File.WriteAllText(configFile, json);
        }

        private void ReloadListView()
        {
            this.listView1.Items.Clear();
            int i = 0;
            foreach (var item in ShowItems)
            {
                ListViewItem lvi = new ListViewItem();
                lvi.ImageIndex = i++;
                lvi.Text = item.id;
                lvi.ToolTipText = item.description;
                lvi.SubItems.Add(item.source);
                lvi.SubItems.Add(item.name);
                lvi.SubItems.Add(item.time.ToString("yy-MM-dd hh:mm"));
                lvi.SubItems.Add(item.tags);
                this.listView1.Items.Add(lvi);
            }
            listView1.Update();
        }

        private void OnMouseClickItem(object sender, MouseEventArgs e)
        {
            MouseEventArgs Mouse_e = (MouseEventArgs)e;
            if (Mouse_e.Button == MouseButtons.Right)
            {
                contextMenuStrip1.Show(MousePosition);
            }
            UpdateSelectedItem();
        }

        private void 编辑ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (selectedItem != null)
            {
                getForm.Show(selectedItem);
            }
        }

        private void OnMouseDoubleClickItem(object sender, EventArgs e)
        {
            ShowItem();
        }

        private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowItem();
        }

        private void ShowItem()
        {
            if (selectedItem != null)
            {
                detailForm.Show(selectedItem);
                Visible = false;
            }
        }

        private void UpdateSelectedItem()
        {
            var item0 = listView1.SelectedItems[0];
            var id = workItems.FindIndex(x => x.id == item0.Text);
            if (workItems.Count > id && id >= 0)
            {
                selectedItem = workItems[id];
                selectedId = id;
            }
        }

        private void 创建ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            getForm.Show(null);
        }

        private void 网址ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (selectedItem != null)
                {
                    System.Diagnostics.Process.Start(selectedItem.web);
                }
            }
            catch (Exception e0)
            {
                MessageBox.Show("链接打开失败:" + e0.Message);
            }
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (selectedItem != null)
            {
                var item = selectedItem;
                var dir = Util.GetBranchFolder(item.id);
                if (Directory.Exists(dir))
                {
                    MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                    DialogResult rt = MessageBox.Show("如需要删除请按确认", "确认删除？", messButton);
                    if (rt == DialogResult.Cancel)
                    {
                        return;
                    }
                    try
                    {
                        System.IO.Directory.Delete(dir, true);
                        workItems.RemoveAt(selectedId);
                        ReloadListView();
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("请检查文件是否被占用！", "删除失败");
                    }
                }
            }
        }

        private void 拷贝分支号ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (selectedItem != null)
            {
                Clipboard.SetText(selectedItem.id);
            }
        }

        private void BackUpMenuItem1_Click(object sender, EventArgs e)
        {
            if (selectedItem != null)
            {
                backupForm.ShowBackUp(selectedItem.fileID, selectedItem.backupInfo);
            }
        }

        private void OnSelectedItemChanged()
        {
            if (selectedItem != null)
            {
                SaveChangedItemToFolder(selectedItem);
            }
        }

        private void 配制ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            settingLinkForm.ShowSetting();
        }
        private void ReLoadCmdListToView(string menuName)
        {
            var menus = menuStrip1.Items.Find(menuName, false);
            if(menus != null && menus.Length > 0)
            {
                 MakeTreeItem(menus[0]as ToolStripMenuItem, configLogic.GetCmdItems(menuName).ToArray());
            }
        }

        private void MakeTreeItem(System.Windows.Forms.ToolStripMenuItem parent, CmdItem[] cmdItems)
        {
            parent.DropDownItems.Clear();
            foreach (var cmdItem in cmdItems)
            {
                System.Windows.Forms.ToolStripMenuItem menuItem = new ToolStripMenuItem();
                menuItem.Name = cmdItem.name;
                menuItem.Text = cmdItem.name;
                menuItem.ToolTipText = cmdItem.text;
                parent.DropDownItems.Add(menuItem);

                menuItem.Click += (sender, arg) =>
                {
                    try
                    {
                        System.Threading.ThreadPool.QueueUserWorkItem((x) =>
                        {
                            agent.RunCmd(cmdItem.text);
                        });
                    }
                    catch (Exception exc)
                    {
                        MessageBox.Show(exc.Message);
                    }
                };

                if (cmdItem.haveChild && cmdItem is ParentCmdItem)
                {
                    MakeTreeItem(menuItem, (cmdItem as ParentCmdItem).childItems);
                }
            }
        }

        private void ReloadLinksToView()
        {
            var names = configLogic.GetProjectNames();
            var paths = configLogic.GetProjectPaths();
            if (names == null || paths == null) return;

            if(menuStrip1.Items.Count > 2)
            {
                //移除非动态菜单
                for (int i = 1; i < menuStrip1.Items.Count - 1; i++) {
                    menuStrip1.Items.RemoveAt(i);
                    i--;
                }
            }

            配制执行ToolStripMenuItem.DropDownItems.Clear();

            for (int i = 0; i < names.Length; i++)
            {
                System.Windows.Forms.ToolStripMenuItem menuItem = new ToolStripMenuItem();
                menuItem.Name = names[i];
                menuItem.Text = names[i];
                menuItem.ToolTipText = paths[i];
                menuStrip1.Items.Insert(i + 1, menuItem);
                MakeTreeItem(menuItem, configLogic.GetCmdItems(names[i]).ToArray());


                System.Windows.Forms.ToolStripMenuItem menuItem1 = new ToolStripMenuItem();
                menuItem1.Name = names[i];
                menuItem1.Text = names[i];
                menuItem1.ToolTipText = paths[i];
                menuItem1.Click += (s,o) =>
                {
                    settingCmdForm.ShowCmdForm(menuItem.Text);
                };
                配制执行ToolStripMenuItem.DropDownItems.Add(menuItem1);
            }
        }

        private void 快捷按扭ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var quicBtnFrom = new QButtonForm();
            quicBtnFrom.Show();
            quicBtnFrom.onClose = LoadButtonCmdTexts;
        }

        private void LoadButtonCmdTexts()
        {
            for (int i = 0; i < configLogic.btnCmds.Count; i++)
            {
                if (quickBtns.Count > i && configLogic.btnCmds[i] != null && !string.IsNullOrEmpty(configLogic.btnCmds[i].name))
                {
                    quickBtns[i].Text = configLogic.btnCmds[i].name;
                }
            }
        }

        private void OnQuickBtnClicked(object sender, EventArgs e)
        {
            if (sender is Button)
            {
                for (int i = 0; i < quickBtns.Count; i++)
                {
                    if(sender == quickBtns[i])
                    {
                        CmdItem cmd = configLogic.GetBtnCmd(i);
                        if (cmd != null)
                        {
                            System.Threading.ThreadPool.QueueUserWorkItem((x) =>
                            {
                                agent.RunCmd(cmd.text);
                            });
                        }
                    }
                }
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            UpdateListByFliter();
        }
    }
}
